# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
from scrapy.exceptions import DropItem
from scrapy.pipelines.images import ImagesPipeline
import scrapy


class imgsPileLine(ImagesPipeline):
    default_headers = {
        'accept': 'image/webp,image/*,*/*;q=0.8',
        'accept-encoding': 'gzip, deflate, sdch, br',
        'accept-language': 'zh-CN,zh;q=0.8,en;q=0.6',
        'cookie': 'bid=yQdC/AzTaCw',
        'referer': '',
        'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36',
    }
    # 对url发送给请求
    def get_media_requests(self, item, info):
        skins_name = item['skins_name']
        heroName = item['heroName']
        version = item['version']
        try:
            if item['win_mainImg']:
                for image_url in item['win_mainImg']:
                    self.default_headers['referer'] = image_url
                    yield scrapy.Request(
                        url=image_url,
                        headers=self.default_headers,
                        meta={'skins_name':skins_name,'heroName':heroName,'version':version}
                    )
        except:
            if item['phone_loadingImg']:
                for image_url in item['phone_loadingImg']:
                    self.default_headers['referer'] = image_url
                    yield scrapy.Request(
                        url=image_url,
                        headers=self.default_headers,
                        meta={'skins_name': skins_name,'heroName':heroName,'version':version}
                    )

    def file_path(self, request, response=None, info=None, *, item=None):
        '''
                这个方法是在图片将要被存储的时候调用，来获取这个图片存储的路径
                :param request:
                :param response:
                :param info:
                :return: 存储路径
        '''
        version = request.meta['version']
        skins_name = request.meta['skins_name']
        heroName = request.meta['heroName']
        file_name = heroName +'/' + skins_name + version + '.jpg'
        if not skins_name:
            raise DropItem('Item contains no images')
        return file_name


    def item_completed(self, results, item, info):
        print('******the request is**********',results)
        return item
